<template>
  <div class="map-box">
    <div id="map_canvas" style="height: 100%; width: 100%"></div>
    <div class="legend-box" :style="{cursor: data?'pointer':'not-allowed'}">
      <div class="legend-item" v-for="(item, index) in legend" :key="index" @click="clickItem(item)">
        <div class="item" :style="{background: active == item.status ? '#ccc' : item.color}"></div>
        <span class="text" :style="{color: active == item.status ? '#ccc' : item.color}">{{ item.name }}</span>
      </div>
    </div>
  </div>
</template>
<script>
/**
 * 参考文档
 * https://www.w3cschool.cn/googleditu/google-maps-events.html
 * https://developers.google.cn/maps/documentation/javascript/examples
 */
  import { getInfoByShop } from '@/api/mapApi.js'
  export default {
    name: 'GGMap',
    props: {
      data: {
        type: [Object, Array],
        default: () => []  // 提供默认值
      },
      carObj: {
        type: [Object, Array],
        default: () => []  // 提供默认值
      }
    },
    data(){
        return{
          show:false,
          center: {},
          markers: [],
          red_icon: require('./static/img/red_icon.png'),
          yellow_icon: require('./static/img/yellow_icon.png'),
          green_icon: require('./static/img/green_icon.png'),
          blue_icon: require('./static/img/blue_icon.png'),
          position: {},
          websock: null,
          legend: [
            {name:'全部', color:'#818181', status: '0'},
            {name:'使用中', color:'#178efc', status: '2'},
            {name:'紧急', color:'#d33e2b', status: '1'},
            {name:'全部可用', color:'#00b407', status: '3'},
            {name:'部分维护', color:'#bfbf00', status: '4'},
          ],
          active: '0'
        }
    },
    watch: {
      // 深度监听对象
      data: {
          handler(newVal, oldVal) {
            this.setData()
          },
          deep: true, // 深度监听
          immediate: true // 立即执行一次
      },
      carObj: {
        handler(newVal, oldVal) {
          this.setData()
        },
        deep: true, // 深度监听
        immediate: true // 立即执行一次
      }
    },
    created(){},
    mounted(){
      this.$eventBus.$on('change-Language', this.init);
      //初始化实例之后调用
      this.setData();
      // this.createMap()
    },
    methods:{
      init(){
        this.legend = [
          {name: this.$t('Byname51'), color:'#818181', status: '0'},
          {name:this.$t('Byname52'), color:'#178efc', status: '2'},
          {name:this.$t('Byname53'), color:'#d33e2b', status: '1'},
          {name:this.$t('Byname54'), color:'#00b407', status: '3'},
          {name:this.$t('Byname55'), color:'#bfbf00', status: '4'},
        ]
      },
      // 辅助方法
      loadScript(src) {
        return new Promise((resolve, reject) => {
          const script = document.createElement('script');
          script.src = src;
          script.onload = resolve;
          script.onerror = reject;
          document.head.appendChild(script);
        });
      },
      clickItem(item) {
        if(!this.data.length) return
        this.active = item.status
        let data = []
        if(item.status == 0){
          data = this.data
        }else{
          data = this.data.filter(val=>val.status == item.status)
        }
        this.markers = data.map(item=>{
          return {
            position: {lng: Number(item.lng), lat: (Number(item.lat))},
            ...item
          }
        })
        this.center = data.length?this.markers[0].position:{lng: 120.5, lat: 30.2};
        this.createMap(); // 设置回调函数为 createMap 方法，该方法将在 API 加载完成后调用。
      },
      setData(){
        this.markers = [...this.data,...this.carObj].map(item=>{
          return {
            position: {lng: Number(item.lng), lat: (Number(item.lat))},
            ...item
          }
        })
        this.center = this.data.length?this.markers[this.markers.length-1].position:{lng: 120.5, lat: 30.2};
        this.createMap(); // 设置回调函数为 createMap 方法，该方法将在 API 加载完成后调用。
      },
      // 图标设置
      setImage(item){
        if(item.status == '1'){
          return this.red_icon
        }else if(item.status == '2'){
          return this.blue_icon
        }else if(item.status == '3'){
          return this.green_icon
        }else if(item.status == '4'){
          return this.yellow_icon
        }
        return this.blue_icon
      },
      setColor(item){
        if(item.status == '1'){
          return '#d33e2b'
        }else if(item.status == '2'){
          return '#178efc'
        }else if(item.status == '3'){
          return '#00b407'
        }else if(item.status == '4'){
          return '#bfbf00'
        }
        return ''
      },
      //  地图实例
      async createMap(){
          //创建地图实例，zoom是缩放比例
        const {ColorScheme} = await google.maps.importLibrary("core")
        let map = new google.maps.Map(document.getElementById('map_canvas'), {
          zoom: 13,
          center: this.center,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          colorScheme: ColorScheme.DARK,
        });
        //这里因为需要很多标记，所以遍历了this.markers（后端给的数据）来循环创建标记
        this.markers.map(item=>{
          if('path' in item){
            map.setZoom(18);
            let marker = new MarkerWithLabel({
              position: item.position,
              // icon: this.icon, //标记自定义图标
              icon: {
                  // url: this.setImage(item), //标记自定义图标
                  url: this.red_icon, //标记自定义图标
                  size: new google.maps.Size(50, 50), // 直接在这里设置图标大小
                  scaledSize: new google.maps.Size(50, 50) // 使用scaledSize也可以达到相同效果
              },
              draggable: false, //不可拖动
              map: map,   //地图实例 
              // labelContent: item.status == '4' ? `P(${item.cars})` : 'P',    //label的内容
              labelAnchor: new google.maps.Point(20, 50),    //label的位置，可以调
              // labelClass: "labels", // the CSS class for the label
              labelStyle: { background: 'red'}
            });
            //点击信息窗口显示
            google.maps.event.addListener(marker, "click", (e)=> { 
              console.log('item', item)
               let iw = null
                  iw = new google.maps.InfoWindow({
                    content: `<div class="content_pop" style="width:500px;display: flex;justify-content: space-between;">
                                <div style="width:35%;height:100%">
                                  <img src="${item.path}" style="width:100%;height:100%" >
                                </div>
                                <div style="width:60%">
                                  <p>${item.shop_title}${item.plate_number}</p>
                                  <p>${item.brand_ftitle}${item.seat_title}</p>
                                  <p>${item.shop_title}</p>
                                  <p>${item.voltage}V</p>
                                </div>
                              </div>`
                  });
                  iw.close(map, marker)
                  iw.open(map, marker)
            })
          }else{
            let marker = new MarkerWithLabel({
              position: item.position,
              // icon: this.icon, //标记自定义图标
              icon: {
                  // url: this.setImage(item), //标记自定义图标
                  url: '', //标记自定义图标
                  size: new google.maps.Size(50, 50), // 直接在这里设置图标大小
                  scaledSize: new google.maps.Size(50, 50) // 使用scaledSize也可以达到相同效果
              },
              draggable: false, //不可拖动
              map: map,   //地图实例 
              labelContent: item.status == '4' ? `P(${item.cars})` : 'P',    //label的内容
              labelAnchor: new google.maps.Point(20, 50),    //label的位置，可以调
              labelClass: "labels", // the CSS class for the label
              labelStyle: { background: this.setColor(item)}
            });
            //点击信息窗口显示
            google.maps.event.addListener(marker, "click", (e)=> { 
              let params = {
                language: "jp",
                shopid: item.id
              }
              let res = getInfoByShop(params).then(res=>{
                if(res.status == '200'){
                  let iw = null
                  iw = new google.maps.InfoWindow({
                    content: `<div class="content_pop">
                                <p>
                                  <span>${this.$t('Byname68')}：${item.title}</span>
                                </p>
                                <p>
                                  <span>${this.$t('Byname69')}：${res.data.cars || 0} ,</span>
                                  <span>${this.$t('Byname52')}：${res.data.running || 0} ,</span>
                                  <span>${this.$t('Byname70')}：${res.data.maintaining || 0} ,</span>
                                  <span>${this.$t('Byname71')}：${res.data.pending || 0} ,</span>
                                  <span style="color:red">紧急：${res.data.urgent_data.length || 0}</span>
                                </p>
                                <p>
                                  <span>紧急：${res.data.urgent_data.map(item=>item.show_car_title).join()}</span>
                                </p>
                              </div>`
                  });
                  iw.close(map, marker)
                  iw.open(map, marker)
                }
              })
            });
          }
        })
      },
    },
  }
</script>
<style scoped lang="scss">
.map-box {
    height: 100%;
    height: 100%;
    position: relative;
    #map_canvas{
      position: absolute;
      top: 0;
      left: 0;
    }
    ::v-deep .gm-style-mtc-bbw {
      display: none;
    }
    
    ::v-deep .gm-svpc {
      display: none;
    }
    ::v-deep .gm-control-active {
      display: none !important;
    }
    
    
    ::v-deep .gm-style .gm-style-iw-c {
      background: rgba(13, 61, 119, 0.852);
      padding: 0;
    }
    ::v-deep .gm-style .gm-style-iw-tc::after{
      background: rgba(13, 61, 119, 0.852);
    }
    ::v-deep .gm-ui-hover-effect{
      width: 30px !important;
      height: 30px !important;
      -webkit-appearance: none; /* Safari and Chrome */
      -moz-appearance: none; /* Firefox */
      appearance: none; /* Standard */
      border: 0 !important;
      &::before{
        content: '×';
        color: #fff;
        font-size: 30px;
        text-align: center;
        line-height: 30px;
      }
    }
    ::v-deep .gm-style-iw-ch{
      padding: 0;
    }
    ::v-deep .gm-style .gm-style-iw-d {
      overflow: auto !important;
    }
    ::v-deep .gm-ui-hover-effect>span{
      display: none !important;
    }
    ::v-deep .labels {
      width: 40px;
      height: 40px;
      color: #fff; /* 文本颜色 */
      // background-color: white; /* 背景颜色 */
      font-family: "Lucida Grande", "Arial", sans-serif; /* 字体 */
      font-size: 16px; /* 字体大小 */
      font-weight: bold; /* 字体粗细 */
      text-align: center; /* 文本对齐方式 */
      // border: 1px solid black; /* 边框 */
      // border-radius: 4px; /* 边框圆角 */
      padding: 1px 6px 0px; /* 内边距 */
      line-height: 35px;
      border-radius: 50%;
    }
    ::v-deep .content_pop {
      color: #fff;
      font-size: 18px;
      padding: 15px;
      padding-top: 0;
      p {
        margin: 0;
      }
    }
    .legend-box{
      cursor: not-allowed;
      position: absolute;
      top: 10px;
      right: 10px;
      background-color: #fff;
      height: 40px;
      display: flex;
      padding: 0 10px;
      .legend-item {
        display: flex;
        align-items: center;
        .item {
          width: 30px;
          height: 15px;
          background-color: red;
        }
        .text {
          color: red;
          margin: 0 5px;
        }
      }
    }
    // background: linear-gradient(180deg, #032750 15%, rgba(3, 41, 86, 0.4) 55%, rgba(2, 37, 76, 0) 99%);
}
</style>